package com.longrise.android.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.longrise.android.FrameworkManager;

import android.os.Environment;

public class LogUtil
{
	private static String logDir = FrameworkManager.getInstance().getAppdir()+"/system";
	private static String logFileName = "Log.txt";
	public static void init(String logdir,String logfilename)
	{
		if(null!=logdir && !"".equals("logdir"))
		{
			logDir = logdir;
		}
		if(null!=logfilename && !"".equals("logfilename"))
		{
			logFileName = logfilename;
		}
		
	}
	public static void write(String txt)
	{
		File file = null;
		RandomAccessFile raf = null;
		SimpleDateFormat df = null;
		StringBuilder sb = null;
		try
		{
			if(null==logDir || "".equals(logDir))return;
			if(null==logFileName || "".equals(logFileName))return;
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				file = new File(Environment.getExternalStorageDirectory(),logDir);
				if(null!=file)
				{
					if (!file.exists()) 
					{
						file.mkdirs();
					}
					file = new File(Environment.getExternalStorageDirectory(),logDir+"/"+logFileName);
					if(null!=file)
					{
						if (!file.exists())
						{
							file.createNewFile();
						}
						if(file.length()>4096000)
						{
							file.delete();
							file.createNewFile();
						}
						if (file.exists())
						{
							raf = new RandomAccessFile(file, "rw");
							if(null!=raf)
							{
								df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								if(null!=df)
								{
									sb = new StringBuilder();
									if(null!=sb)
									{
										sb.append(df.format(new Date()));
										sb.append(" ");
										sb.append(txt);
										sb.append("\r\n");
										raf.seek(file.length());
										raf.write(sb.toString().getBytes("utf-8"));
										raf.close();
									}
								}
								
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			df = null;
			sb = null;
			raf = null;
			file = null;
			txt = null;
		}
	}
}
